package com.kiloai.base.okgohttp.callback;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;

import com.kiloai.base.R;

import com.kiloai.base.utils.NetWorkInfo;
import com.kiloai.base.utils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.lang.reflect.Type;

/**
 * Created by david on 2018/3/5.
 */

public abstract class JsonDialogCallback<T> extends JsonCallback<T> {
    private String TAG = "JsonDialogCallback";

    private Dialog dialog;
    private Context context;

    public JsonDialogCallback(Context context) {
        this.context = context;
    }

    public JsonDialogCallback(Context cont, Type type) {
        this.context = cont;
        super.type = type;
        dialog = new Dialog(context, R.style.Loding);
        dialog.setContentView(R.layout.dialog_progress_loading);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                /*用户点击取消按钮时 取消对应请求任务*/
                OkGo.getInstance().cancelTag(context.getClass().getSimpleName());
            }
        });
    }

    @Override
    public void onError(Response<T> response) {
        super.onError(response);
        if (!NetWorkInfo.isConn(context)) {
            ToastUtils.show(context, "网络断开连接，请检查网络");//error:null
            return;
        }
        String msg = response.getException().getMessage().toString();
        if (msg.contains("error") && msg.length() > 6) {
            ToastUtils.show(context, msg.substring(6));//error:null
        }
    }

    @Override
    public void onStart(Request request) {
        super.onStart(request);

        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
